package top.zymall.user.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zy.common.zymallcommon.utils.exception.ExceptionEnum;
import top.zy.common.zymallcommon.utils.exception.ZymalException;
import top.zy.common.zymallcommon.utils.util.JsonUtils;
import top.zy.common.zymallcommon.utils.util.NumberUtils;
import top.zymall.user.entity.User;
import top.zymall.user.mapper.UserMapper;
import top.zymall.user.mq.SendMessage;
import top.zymall.user.util.RedisUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:44 2019/7/10
 */
@Service
public class UserServiceImpl implements UserService {

    private static final int NOT_USER = 0;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SendMessage sendMessage;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Boolean checkUserData(String param, Integer type) {
        User user=new User();
        switch (type){
            case 1: user.setUsername(param);
            break;
            case 2:user.setPhone(param);
            break;
            default:
                throw new ZymalException("aaaaa",200);
        }
        return userMapper.selectCount(user)==NOT_USER;
    }

    @Override
    public void sendVerify(String phone) {
        String code = NumberUtils.generateCode(6);
        int result = redisUtils.saveVerifyCode(phone, code, 60);
        if (result==1){
            throw new ZymalException("当前手机号超过使用次数");
        }
        if (result==2){
            throw new ZymalException("当前验证码未过期");
        }
        Map<String,String> map=new HashMap<>();
        map.put("mobile",phone);
        map.put("code",code);
        String message = JSONObject.toJSONString(map);
        sendMessage.sendMessageToMq(message);
    }
}
